/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.rest;

import com.tfb.rong.Device;
import com.tfb.rong.DeviceDataWithBLOBs;
import com.tfb.service.UserAssessmentI;
import com.tfb.service.utility.AppConst;
import com.tfb.service.utility.HttpUtil;
import com.tfb.service.utility.JsonUtil;
import com.tfb.service.utility.Utils;
import com.tlr.device.model.LocationCard;
import com.tlr.device.model.Result;
import com.tlr.device.service.DeviceDatabaseService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Path("/vehicle")
public class VehiclePositionService {

    private static final Logger log = Logger.getLogger(UserResource.class);
    @Context
    ServletContext context;
    UserAssessmentI userService;
    DeviceDatabaseService deviceService;

    private synchronized void initDatabaseService() {
        if (userService == null) {
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
            userService = (UserAssessmentI) ac.getBean("userAssessmentService");
            deviceService = (DeviceDatabaseService) ac.getBean("deviceDatabaseService");
        }
    }

    @Path("/position")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<LocationCard>> getPosition(@Context HttpServletRequest request) {
        try {
            initDatabaseService();
            List<Device> devices = deviceService.getDeviceMapper().selectVehicleDeviceByStatus(1);
            devices.addAll(deviceService.getDeviceMapper().selectVehicleDeviceByStatus(2));
            devices.addAll(deviceService.getDeviceMapper().selectVehicleDeviceByStatus(3));
            DeviceDataWithBLOBs ddb = new DeviceDataWithBLOBs();
            List<LocationCard> locations = new ArrayList<>();
            for (Device device : devices) {
                ddb.setDeviceid(device.getDevicemac());
                List<DeviceDataWithBLOBs> deviceDataList = deviceService.getDeviceDataMapper().selectLastDeviceData(ddb);
                LocationCard lc = new LocationCard();
                lc.setStorage_id(device.getDeviceid());
                lc.setDevice_id(device.getDevicemac());
                lc.setPlate(device.getBindname());
                lc.setMobile(device.getUserTel());
                lc.setOwner(device.getUserName());
                if (lc.getOwner() == null || lc.getOwner().isEmpty()) {
                    lc.setPlate("未绑定");
                    lc.setMobile("未绑定");
                    lc.setOwner("未绑定");
                }
                if (deviceDataList.isEmpty()) {
                    lc.setStatus(0);
                    lc.setStatus_label("无位置信息");
                } else if (device.getStatus() == 3) {
                    lc.setStatus(device.getStatus());
                    lc.setStatus_label("停止服务");
                } else if (device.getStatus() == 2) {
                    lc.setStatus(device.getStatus());
                    lc.setStatus_label("等待服务");
                } else if (device.getStatus() == 1) {
                    lc.setStatus(device.getStatus());
                    lc.setStatus_label("正常服务中");
                }

                if (!deviceDataList.isEmpty()) {
                    DeviceDataWithBLOBs dd = deviceDataList.get(0);
                    lc.setLng(dd.getLng());
                    lc.setLat(dd.getLat());
                }
                locations.add(lc);
            }
            return new Result<>(0, "OK", locations);
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "更新位置信息错误，请联系管理员");
        }
    }

    @Path("/set_status")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> updateStatus(@Context HttpServletRequest request,
                                       @QueryParam("status") int status) {
        try {
            log.info("Set car service status: " + status);
            initDatabaseService();
            String userID = HttpUtil.getUserDBID(request);
            List<Device> carList = deviceService.getAllBindDevice(userID, 2);
            if (carList.isEmpty()) {
                return new Result<>(500, "没有绑定服务车信息");
            }
            Device bindCar = carList.get(0);
            bindCar.setStatus(status);
            int ret = deviceService.getDeviceMapper().updateByPrimaryKeySelective(bindCar);
            log.info("Ret: " + ret);
            return new Result<>(0, "OK");
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "更新服务状态错误");
        }
    }

    @Path("/get_status")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> getStatus(@Context HttpServletRequest request) {
        try {
            initDatabaseService();
            String userID = HttpUtil.getUserDBID(request);
            log.info("User: " + userID);
            List<Device> carList = deviceService.getAllBindDevice(userID, 2);
            if (carList.isEmpty()) {
                return new Result<>(500, "没有绑定服务车信息");
            }
            Device bindCar = carList.get(0);
            return new Result<>(0, "OK", Integer.toString(bindCar.getStatus()));
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "读取服务状态错误");
        }
    }

    @Path("/position")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> updatePosition(@Context HttpServletRequest request,
                                         String message) {
        try {
            log.info("position: " + message);
            String userID = HttpUtil.getUserDBID(request);
            JsonNode positionInfo = JsonUtil.createJson(message);
            initDatabaseService();
            List<Device> carList = deviceService.getAllBindDevice(userID, 2);
            if (carList.isEmpty()) {
                return new Result<>(500, "没有绑定服务车信息");
            }
            Device bindCar = carList.get(0);
            DeviceDataWithBLOBs ddb = new DeviceDataWithBLOBs();
            ddb.setDeviceid(bindCar.getDevicemac()); // car plate here as mac
            ddb.setLng(positionInfo.get("longitude").asText());
            ddb.setLat(positionInfo.get("latitude").asText());
            ddb.setGettime(Calendar.getInstance().getTime());
            ddb.setDatatype(AppConst.POSITION_TYPE);
            deviceService.insertDeviceDataSelective(ddb);
            deviceService.deleteDataBefore6Hours(ddb);
            return new Result<>(0, "OK");
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "更新位置信息错误，请联系管理员");
        }
    }

}
